import React, { Fragment } from 'react';
import ReactEcharts from '@/components/Echarts';
import flattenDeep from 'lodash/flattenDeep';

const getTooltipValue = (data, mapping) =>
    data
        .map(item => {
            if (item.value > 0) {
                return `<li>${mapping[item.name + item.seriesName]}: ${item.value}个</li>`;
            }
            return null;
        })
        .join('\n');
const getOption = ({ yAxisData, mapping, a }) => ({
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'none' // 默认为直线，可选为：'line' | 'shadow'
        },
        formatter: data => {
            console.log('kongqi', data);
            let tooltipShow = 0;
            data.forEach(item => {
                if (item.value > 0) {
                    tooltipShow = 1;
                }
            });
            return tooltipShow > 0
                ? `<ul>
                        ${getTooltipValue(data, mapping)}
                    </ul>`
                : null;
        }
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis: {
        type: 'value'
    },
    yAxis: {
        type: 'category',
        data: yAxisData
    },
    series: a.map((x, index) => ({
        name: index,
        type: 'bar',
        stack: '总量',
        // label: {
        //     show: true,
        //     position: 'insideRight',
        //     formatter: data => {
        //         if (data.name && data.value > 0) {
        //             return `${mapping[data.name + data.seriesName]}:${data.value}个`;
        //         } else {
        //             return null;
        //         }
        //     }
        // },
        data: x
    }))
});

const Ygzj = ({ data }) => {
    // 较为麻烦的数据转换
    const extraHandler = () => {
        const result = [];
        const lengthAry = Object.values(data).map(item => item.length);
        const maxLength = Math.max(...lengthAry);

        const dataValues = Object.values(data);
        for (let i = 0; i < maxLength; i += 1) {
            result[i] = [];
        }
        result.forEach((item, index) => {
            dataValues.forEach((objectAry, objectIndex) => {
                result[index][objectIndex] = objectAry[index] ? objectAry[index].value : 0;
            });
        });
        return result;
    };
    const yAxisData = Object.keys(data);
    const getMapping = yAxisData.map(item => data[item].map((x, index) => ({ [`${item}${index}`]: x.name })));
    const mapping = flattenDeep(getMapping).reduce((prev, curr) => ({ ...prev, ...curr }), {});
    const a = extraHandler();

    return (
        <Fragment>
            <ReactEcharts option={getOption({ yAxisData, mapping, a })} />
        </Fragment>
    );
};

export default Ygzj;
